<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/16
 * Time: 15:23
 */

namespace app\storage\model;


use service\k3\K3ReaderFactory;
use think\Db;
use think\Model;

class SupplierMaterielModel extends Model
{
    protected $table = 'iwh_supplier_materiel';
    protected $pk = 'uuid';


    public function updateInventoryFromK3($supplierId){
        $supplier = $this->distinct(true)->column('supplier_id');
        $supplierId = empty($supplierId)?array_filter($supplier):$supplierId;
        $supplierCount = K3ReaderFactory::read('inventory',$supplierId);
        $supplierArr = array_unique(array_column($supplierCount, 'supplier_id'));

        Db::startTrans();

        $addSupplierSub = $deleteSupplierSub = true;
        if (!empty($supplierArr)) {
            $map['supplier_id'] = ['in', $supplierArr];
            $deleteSupplierSub = Db::table('iwh_supplier_materiel')->where($map)->delete();
            $addSupplierSub = Db::table('iwh_supplier_materiel')->insertAll($supplierCount);
        }elseif(empty($supplierArr) &&!empty($supplierId)){
            $deleteSupplierSub = Db::table('iwh_supplier_materiel')->whereIn('supplier_id',$supplierId)->delete();
        }

        if (false !== $addSupplierSub && false !== $deleteSupplierSub) {
            Db::commit();
            return ret_template(true,'更新成功');
        } else {
            Db::rollback();
            return ret_template(true,'更新失败');
        }
    }
}